package pers.rcl.interceptor;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.login.SsoWebLoginHelper;
import com.xxl.sso.core.user.XxlSsoUser;

import pers.rcl.utils.xx;

public class SysInterceptor implements Interceptor{

	/**
     * 登录拦截排除URI<br>
     * ? 匹配任何单字符<br>
     * * 匹配0或者任意数量的字符<br>
     * ** 匹配0或者更多的目录 <br>
     */
    public static ArrayList<String> excludes = new ArrayList<String>();

    static {
        excludes.add("/doLogin");
        excludes.add("/swagger/*");
        excludes.add("/swagger");
    }

    public void intercept(Invocation inv) {
        try {
            //把request注入ThreadLocal,用于获取session容器的对象
            Controller ctrl = inv.getController();
            xx.setRequest(ctrl.getRequest());

            String uri = inv.getActionKey();
            
            HttpServletRequest request = ctrl.getRequest();
            HttpServletResponse response = ctrl.getResponse();
            
            // valid login user, cookie + redirect
            XxlSsoUser xxlUser = SsoWebLoginHelper.loginCheck(request, response);
         // valid login fail
            if (xxlUser == null) {

                String header = request.getHeader("content-type");
                boolean isJson=  header!=null && header.contains("json");
                if (isJson) {

                    // json msg
                	response.setContentType("application/json;charset=utf-8");
                	response.getWriter().println("{\"code\":"+Conf.SSO_LOGIN_FAIL_RESULT.getCode()+", \"msg\":\""+ Conf.SSO_LOGIN_FAIL_RESULT.getMsg() +"\"}");
                    return;
                } else {

                    // total link
                    String link = request.getRequestURL().toString();

                    // redirect logout
                    String loginPageUrl = xx.getConfigValue("xxl.sso.server")
                            + "?" + Conf.REDIRECT_URL + "=" + link;

                  response.sendRedirect(loginPageUrl);
                  return;
                }

            }

            // ser sso user
            ctrl.setAttr(Conf.SSO_USER, xxlUser);
            
            inv.invoke();
            // 检查登录状态
       /*     ctrl = inv.getController();
            User user = ctrl.getSessionAttr(SysConst.USER);
            if (user == null) {
                LogKit.info("用户没有登录");
                ctrl.setAttr("siteName", xx.getConfig("site.name"));
                // 返回登录页面
                ctrl.render("/WEB-INF/views/login.html");
            } else {
                inv.invoke();
            }*/
        } catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
        	//防止线程一直运行，得不到回收，从而造成内存的泄露
            xx.removeRequest();
        }
    }
}
